<template>
  <div class="shopList">
    <el-table :data="tableData" style="width: 100%">
      <el-table-column type="expand">
        <template slot-scope="props">
          <el-table :data="props.row.sonData" style="width: 90%;margin-left:40px" :cell-style="cellStyle">
            <el-table-column
                v-for="(value, index) in sonColumns"
                :key="index"
                :label="value.name"
                :prop="value.propName">
            </el-table-column>
            <el-table-column label="操作">
              <template slot-scope="scope">
                <el-button v-if="scope.row.taskStatus == '未完成'" @click="handleEdit(scope.$index, scope.row)">提交</el-button>
                <el-button v-if="scope.row.taskStatus == '未完成'" type="danger" @click="handleDelete(scope.$index, scope.row)">删除</el-button>
              </template>
            </el-table-column>
          </el-table>
          <div v-if="props.row.showNewTask" label="新增任务" class="new-task-row">
            <div class="new-task-item">
              <el-input v-model="taskName" placeholder="任务名"></el-input>
            </div>
            <div class="new-task-item">
              <el-input v-model="taskPercentage" placeholder="任务权重"></el-input>
            </div>
            <div class="new-task-item">
              <el-select v-model="assignedToId" placeholder="选择负责人">
                <el-option
                    v-for="member in props.row.newTask.members"
                    :key="member.memberId"
                    :label="member.memberName + ' - ' + member.memberJob"
                    :value="member.memberId">
                </el-option>
              </el-select>
            </div>
            <div class="new-task-item">
              <el-date-picker v-model="startDate" type="date" placeholder="开始日期"></el-date-picker>
            </div>
            <div class="new-task-item">
              <el-date-picker v-model="dueDate" type="date" placeholder="结束日期"></el-date-picker>
            </div>
            <div class="new-task-item">
              <el-button @click="handleConfirmAddTask(props.row)">确认新增</el-button>
            </div>
          </div>
        </template>
      </el-table-column>
      <el-table-column
          v-for="(value, key, index) in parentsCloums"
          :key="index"
          :label="value.name"
          :prop="value.propName">
      </el-table-column>
      <el-table-column label="操作">
        <template slot-scope="props">
          <el-button v-if="props.row.projectStatus == '在途'" type="primary" @click="handleAddTask(props.row)">新增任务</el-button>
        </template>
      </el-table-column>
    </el-table>
  </div>
</template>

<script>
import http from "@/api/http";

export default {
  name: "ManagerTask",
  data() {
    return {
      taskName: '',
      taskPercentage: '',
      assignedToId: '',
      startDate: '',
      dueDate: '',
      userName:'',
      parentsCloums: [ //外层table的表头
        {
          name: "项目号",
          id: "1",
          propName: "projectId",
        }, {
          name: "项目名称",
          id: "2",
          propName: "projectName",
        }, {
          name: "项目状态",
          id: "3",
          propName: "projectStatus",
        }
      ],
      tableData: [], //外层table的数据
      sonColumns: [ //内层table的表头
        {
          name: "任务名",
          id: "2",
          propName: "taskName",
        },
        {
          name: "任务负责人",
          id: "3",
          propName: "memberName",
        },
        {
          name: "任务权重",
          id: "4",
          propName: "taskPercentage",
        },
        {
          name: "任务状态",
          id: "5",
          propName: "taskStatus",
        }
      ]
    }
  },
  methods: {
    handleEdit(index, row) {
      // 提交的逻辑
      http.put(`/api/tasks/update/${row.taskId}`, row)
          .then(res => {
            this.$message.success("任务更新成功");
            this.fetchProjectsAndTask(); // 更新项目和任务列表
          })
          .catch(error => {
            console.error(`Error updating task ${row.taskId}:`, error);
            this.$message.error("任务更新失败");
          });
    },
    handleDelete(index, row) {
      // 删除的逻辑
      http.delete(`/api/tasks/remove/${row.taskId}`)
          .then(res => {
            this.$message.success("任务删除成功");
            this.fetchProjectsAndTask(); // 更新项目和任务列表
          })
          .catch(error => {
            console.error(`Error deleting task ${row.taskId}:`, error);
            this.$message.error("任务删除失败");
          });
    },
    handleAddTask(row) {
      // 新增任务的逻辑
      http.get(`/api/members/${row.projectId}/members`)
          .then(res => {
            const members = res;
            row.showNewTask = !row.showNewTask;
            row.newTask = {
              members: members
            };
            this.taskName = '';
            this.taskPercentage = '';
            this.assignedToId = '';
            this.startDate = '';
            this.dueDate = '';
            // 确保 Vue 能够检测到 newTask 的变化
            this.$set(row, 'newTask', row.newTask);
          })
          .catch(error => {
            console.error(`Error fetching members for project ${row.projectId}:`, error);
          });
    },
    handleConfirmAddTask(row) {
      // 确认新增任务的逻辑
      const newTask = row.newTask;
      const payload = {
        taskName: this.taskName,
        projectId: row.projectId,
        assignedToId: this.assignedToId,
        taskPercentage: this.taskPercentage,
        startDate: this.startDate,
        dueDate: this.dueDate
      };
      http.post(`/api/tasks/add`, payload)
          .then(res => {
            this.$message.success("任务新增成功");
            this.fetchProjectsAndTask(); // 更新项目和任务列表
          })
          .catch(error => {
            console.error("Error adding new task:", error);
            this.$message.error("任务新增失败");
          });
    },
    async fetchProjectsAndTask() {
      try {
        // 获取所有项目的数据
        const projectsResponse = await http.get('/api/tasks/projects');
        const projects = projectsResponse;

        // 使用 Promise.all 并行获取所有项目的任务信息
        const projectsWithTasks = await Promise.all(projects.map(async (project) => {
          try {
            const tasksResponse = await http.get(`/api/tasks/project/${project.projectId}/tasks`);
            const tasks = tasksResponse || [];
            return {
              ...project,
              sonData: tasks,
              showNewTask: false
            };
          } catch (error) {
            console.error(`Error fetching tasks for project ${project.projectId}:`, error);
            return {
              ...project,
              sonData: [],
              showNewTask: false
            };
          }
        }));
        this.tableData = projectsWithTasks;
      } catch (error) {
        console.error('Error fetching projects:', error);
      }
    },
    getName(){
      http.get('/api/userinfo')
          .then(res=>{
            this.userName=res.userName;
            console.log('getUSER',this.userName)
            console.log('getUSER',res.userName);
          })
          .catch(error=>{
            console.error('获取用户名失败');
            this.$message.error("获取用户名失败");
          })
    },
    cellStyle(){//根据情况显示背景色
      return 'background:#F3F6FF'
    }
  },
  created() {
    this.fetchProjectsAndTask();
  }
}
</script>

<style>
.demo-table-expand {
  font-size: 0;
}

.demo-table-expand label {
  width: 90px;
  color: #99a9bf;
}

.demo-table-expand .el-form-item {
  margin-right: 0;
  margin-bottom: 0;
  width: 50%;
}

.new-task-row {
  display: flex;
  flex-wrap: wrap;
  align-items: center;
}

.new-task-item {
  margin-right: 10px;
  margin-bottom: 10px;
}
</style>
